<template>
  <div>
    <div>
      <el-form :inline="true" style="margin: 20px">
        <el-form-item label="登录名称:">
          <el-input v-model="queryParam.loginName" placeholder="请输入登录名称模糊查询" clearable />
        </el-form-item>
        <el-form-item label="用户姓名:">
          <el-input v-model="queryParam.username" placeholder="请输入用户姓名模糊查询" clearable />
        </el-form-item>
        <el-button type="primary" @click="searchQuery">查询</el-button>
        <el-button @click="searchReset">重置</el-button>
      </el-form>
    </div>
    <div>
      <el-button
        type="primary"
        icon="el-icon-plus"
        style="position:relative;left:20px;top:-25px"
        @click="handleAdd"
      >新增</el-button>

      <el-dropdown style="position:relative;left:30px;top:-25px">
        <el-button>
          批量操作<i class="el-icon-arrow-down el-icon--right" />
        </el-button>
        <el-dropdown-menu slot="dropdown">
          <el-dropdown-item icon="el-icon-delete" @click.native="batchDel">删除</el-dropdown-item>
          <el-dropdown-item icon="el-icon-success" @click.native="batchSetStatus(0)">启用</el-dropdown-item>
          <el-dropdown-item icon="el-icon-error" @click.native="batchSetStatus(1)">禁用</el-dropdown-item>
        </el-dropdown-menu>
      </el-dropdown>
    </div>
    <div class="table">
      <!-- table区域 -->
      <el-table
        ref="multipleTable"
        :data="userList"
        tooltip-effect="dark"
        border
        style="width: 1240px;"
        @selection-change="handleSelectionChange"
      >
        <el-table-column type="selection" align="center" width="120px" />
        <el-table-column prop="id" label="#" align="center" />
        <el-table-column prop="loginName" label="登录名称" />
        <el-table-column prop="username" label="用户姓名" />
        <el-table-column prop="type" label="用户类型">
          <template slot-scope="scope">
              <div v-if="scope.row.name == '租户'">
                租户
              </div>
              <div v-else>
                普通
              </div>
          </template>
        </el-table-column>
        <el-table-column prop="name" label="角色" />
        <!-- <el-table-column prop="zzz" label="机构"> </el-table-column> -->
        <el-table-column prop="phonenum" width="130px" label="电话号码" />
        <el-table-column prop="sort" label="排序" />
        <el-table-column label="状态" align="center">
          <template slot-scope="scope">
            <el-tag v-if="scope.row.status === 2" type="danger">封禁</el-tag>
            <el-tag v-if="scope.row.status === 1" type="danger">禁用</el-tag>
            <el-tag v-if="scope.row.status === 0" type="success">启用</el-tag>
          </template>
        </el-table-column>
        <el-table-column label="操作" align="center" width="300px">
          <template slot-scope="scope">
            <el-button type="text" icon="el-icon-edit" @click="edit(scope.row)">编辑</el-button>
            <el-button
              type="text"
              icon="el-icon-delete"
              style="color: red;"
              @click="removeById(scope.row)"
            >删除</el-button>
            <el-popconfirm title="确定要重置密码吗？" @confirm="resetPwd(scope.row)" @cancel="visible = false">
              <el-button slot="reference" type="text" icon="el-icon-refresh-left">重置密码</el-button>
            </el-popconfirm>
          </template>
        </el-table-column>
      </el-table>
      <el-pagination
        style="float: right"
        :current-page="current"
        :page-sizes="[5, 10, 15, 20]"
        :page-size="pageSize"
        class="page"
        layout="total, sizes, prev, pager, next, jumper"
        :total="total"
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
      />
    </div>
    <div>
      <!-- Form -->
      <el-dialog :title.sync="dialogTitle" :visible.sync="dialogFormVisible">
        <el-form ref="form" :model="form" :rules="rules">
          <el-form-item label="登录名称:" :required="true" prop="loginName">
            <el-input v-model="form.loginName" style="width:600px" placeholder="请输入登录名称"><template
              #suffix
            >初始密码：123456</template></el-input>
          </el-form-item>
          <el-form-item label="用户姓名:" :required="true" prop="username">
            <el-input v-model="form.username" style="width:600px" placeholder="请输入用户姓名" />
          </el-form-item>
          <el-form-item label="角色:" :required="true" style="padding-left:30px" prop="name">
            <el-select v-show="aa" v-model="form.name" placeholder="请选择角色" style="width:500px">
              <el-option v-for="item in users" :key="item.id" :label="item.name" :value="item.name">{{
                item.name
              }}</el-option>
            </el-select>
            <div v-show="!aa">{{ form.name }}</div>
          </el-form-item>
          <!-- <el-form-item label="机构:" style="padding-left:40px">
                        <el-select v-model="form.priceLimit" placeholder="请选择机构" style="width:500px">
                            <el-option label="1" value="1"></el-option>
                        </el-select>
                    </el-form-item> -->
          <el-form-item label="职位:" style="padding-left:40px">
            <el-input v-model="form.position" style="width:600px" placeholder="请输入职位" />
          </el-form-item>
          <el-form-item label="电话号码:" style="padding-left:10px">
            <el-input v-model="form.phonenum" style="width:600px" placeholder="请输入电话号码" />
          </el-form-item>
          <el-form-item label="电子邮箱:" style="padding-left:10px">
            <el-input v-model="form.email" style="width:600px" placeholder="请输入电子邮箱" />
          </el-form-item>
          <el-form-item label="排序:" style="padding-left:40px">
            <el-input v-model="form.sort" style="width:600px" placeholder="请输入排序" />
          </el-form-item>
          <el-form-item label="描述:" style="padding-left:35px">
            <el-input v-model="form.description" type="textarea" style="width:600px" placeholder="请输入描述" />
          </el-form-item>
        </el-form>
        <div slot="footer" class="dialog-footer">
          <el-button @click="cancel">取 消</el-button>
          <el-button type="primary" @click="submitForm('form')">确 定</el-button>
        </div>
      </el-dialog>
    </div>
  </div>
</template>

<script>
import userApi from '@/api/user'

export default {
  data() {
    return {
      // 查询条件
      queryParam: {
        loginName: '',
        userName: ''

      },
      checkParam: {
        id: '',
        loginName: undefined,
        userName: undefined
      },
      form: {
        id: '',
        loginName: '',
        username: '',
        priceLimit: '',
        description: '',
        name: '',
        position: '',
        phonenum: '',
        email: '',
        sort: ''
      },
      rules: {
        loginName: [{ required: true, message: '请输入登录名称', trigger: 'blur' },
          { validator: this.checkIsLoginNameExist, trigger: 'blur' }],
        username: [{ required: true, message: '请输入用户姓名', trigger: 'blur' },
          { validator: this.checkIsUserNameExist, trigger: 'blur' }],
        name: [{ required: true, message: '请选择角色', trigger: 'blur' }]
      },
      users: [],
      userList: [],
      multipleSelection: [],
      current: 1,
      pageSize: 5,
      total: 0,
      dialogFormVisible: false,
      dialogTitle: '新增',
      visible: false,
      aa: true
    }
  },
  created() {
    this.list()
  },
  mounted() {
    this.selectRoles()
  },
  methods: {
    checkIsLoginNameExist(rule, value, callback) {
      this.checkParam = {}
      this.checkParam.id = this.form.id
      this.checkParam.loginName = this.form.loginName
      userApi.checkIsLoginNameExist(this.checkParam)
        .then(res => {
          if (res.status) {
            callback(new Error('登录名称已存在'))
          } else {
            callback()
          }
        })
    },
    checkIsUserNameExist(rule, value, callback) {
      this.checkParam = {}
      this.checkParam.id = this.form.id
      this.checkParam.userName = this.form.username
      userApi.checkIsUserNameExist(this.checkParam)
        .then(res => {
          if (res.status) {
            callback(new Error('用户姓名已存在'))
          } else {
            callback()
          }
        })
    },
    cancel() {
      this.dialogFormVisible = false
    },
    selectRoles() {
      userApi.selectRole().then((res) => {
        this.users = res.data
      })
    },
    // 查看详细
    edit(row) {
      this.dialogTitle = '修改'
      this.aa = false
      this.dialogFormVisible = true
      this.form = JSON.parse(JSON.stringify(row))
      // 清除自动触发的表单验证
      this.$nextTick(() => {
        this.$refs['form'].clearValidate()
      })
    },
    list() {
      userApi.userListPage(this.current, this.pageSize, this.queryParam).then((res) => {
        this.userList = res.data.records
        this.pageSize = res.data.size
        this.current = res.data.current
        this.total = res.data.total
      })
    },
    handleAdd() {
      this.aa = true
      this.dialogFormVisible = true
      this.dialogTitle = '新增'
      this.form.id = undefined
      this.form = {}
      // 清除自动触发的表单验证
      this.$nextTick(() => {
        this.$refs['form'].clearValidate()
      })
    },
    handleSizeChange(val) {
      this.pageSize = val
      this.list()
    },
    handleCurrentChange(val) {
      this.current = val
      this.list()
    },
    searchQuery() {
      this.list()
    },
    searchReset() {
      this.queryParam = {
        name: ''
      }
    },
    handleSelectionChange(val) {
      this.multipleSelection = val
    },
    submitForm(form) {
      this.$refs[form].validate((valid) => { // 开启校验
        if (valid) { // 如果校验通过，请求接口，允许提交表单
          if (this.form.id === undefined) {
            userApi.addUser(this.form)
              .then(res => {
                this.$message({
                  type: 'success',
                  message: '添加成功'
                })
                this.form = {}
                this.dialogFormVisible = false
                this.list()
              })
          } else {
            userApi.updateUser(this.form)
              .then(res => {
                this.$message({
                  type: 'success',
                  message: '修改成功'
                })
              })
          }
          this.form = {}
          this.dialogFormVisible = false
          this.list()
        }
      })
    },
    resetPwd(row) {
      this.visible = false
      userApi.resetPwd(row.id).then(res => { // 接口
        this.$message({
          type: 'success',
          message: '修改成功!'
        })
        this.list()// 成功后初始化查询列表
      })
    },
    batchDel() {
      if (this.multipleSelection === '') {
        this.$message.warning('请至少选择一条数据进行删除！')
      } else {
        this.$confirm('此操作将永久删除该权限，是否继续？', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning',
          center: true
        }).then(() => {
          // 声明空数组,这里的数组是后端需要的数据
          const arrray = []
          // 遍历勾选数据取自己需要的id等这里是和后端需要的参数对应
          for (let i = 0; i < this.multipleSelection.length; i++) {
            arrray.push(this.multipleSelection[i].id)// 把取出的对象push到数组里
          }
          userApi.deleteBatch(arrray).then(res => { // 接口
            this.list()// 删完成功后初始化查询列表
          })
        })
      }
    },
    batchSetStatus(status) {
      if (this.multipleSelection === '') {
        this.$message.warning('请至少选择一条数据进行修改！')
      } else {
        this.$confirm('是否修改客户状态?', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
          const arrray = []
          // 遍历勾选数据取自己需要的id等这里是和后端需要的参数对应
          for (let i = 0; i < this.multipleSelection.length; i++) {
            arrray.push(this.multipleSelection[i].id)// 把取出的对象push到数组里
          }
          userApi.batchSetStatus(arrray, status)
            .then(res => {
              this.$message({
                type: 'success',
                message: '修改成功!'
              })
              this.list()
            })
        })
      }
    },
    removeById(row) {
      this.$confirm('此操作将永久删除该数据, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        userApi.deleteById(row.id)
          .then(res => {
            this.$message({
              type: 'success',
              message: '删除成功!'
            })
          })
        this.list()
      })
    }
  }
}
</script>

<style>
.table {
  position: relative;
  left: 20px;
}

.page {
  position: relative;
  left: -100px;
  top: 10px;
}
</style>
